package com.xk.ucs.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常拦截
 * @Author 01387843
 * @Date 2022/6/22
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({ApplicationException.class})
    @ResponseBody
    public Result<String> applicationExceptionHandler(HttpServletRequest req, HttpServletResponse res, ApplicationException e){
        log.error("应用异常：",e);
        Result<String> error = new Result<>();
        error.setCode(e.getCode());
        error.setMessage(e.getMessage());
        error.setInfo(ErrorEnum.getInfo(e.getCode()));
        return error;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result<String> defaultErrorHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        if (!(e instanceof MethodArgumentNotValidException)) {
            log.error("defaultErrorHandler system error: URL:{}", req.getRequestURI(),e);
        } else {
            log.error("defaultErrorHandler system error: URL:{}",req.getRequestURI(), e);
        }

        StringBuilder errorMsg = new StringBuilder();
        Iterator iterator;
        if (e instanceof MethodArgumentNotValidException) {
            List<ObjectError> allErrors = ((MethodArgumentNotValidException)e).getBindingResult().getAllErrors();
            errorMsg.append("参数异常：");

            ObjectError error;
            for(iterator = allErrors.iterator(); iterator.hasNext(); errorMsg.append(error.getDefaultMessage())) {
                error = (ObjectError)iterator.next();
                errorMsg.append('\n');
                if (error instanceof FieldError) {
                    errorMsg.append("field:").append(((FieldError)error).getField()).append(",");
                }
            }
        } else {
            errorMsg.append("系统异常，请联系管理员。");
        }
        Result<String> error = new Result<>();
        error.setCode("500");
        error.setMessage(errorMsg.toString());
        error.setInfo("系统异常，请联系管理员");
        return error;
    }
}
